import { itag } from "../itag/index.js";
import { createElements, define, type CustomElement } from "../itag/util.js";
import { MessageElement } from "./MessageElement.js";
import * as styles from "./styles.js";

interface Log {
    message: string;
}

/**
 * LogElement - 用于显示日志的自定义HTML元素
 * 你这只组件的主要功能有显示发送的 hex 数据然以及 hex 数据
 */
export class LoggerElement extends HTMLElement implements CustomElement {
    /**
     * 元素表
     */
    readonly #elms = createElements({
        container: "div",
    });

    /**
     * 日志列表
     */
    #logs: Log[] = [];

    /**
     * 日志元素列表
     */
    #elements: MessageElement[] = [];

    constructor() {
        super();
        const sr = this.attachShadow({ mode: "open" });
        sr.adoptedStyleSheets.push(styles.sheet);

        // 使用 iTag 构建 DOM
        itag`
${sr}
    ${this.#elms.container} .${styles.container}
`;
        for (let i = 0; i < 20; i++) {
            const elm = new MessageElement();
            this.#elements.push(elm);
            this.#elms.container.appendChild(elm);
        }
    }

    connectedCallback(): void {
        this.#updateLogs();
    }

    log(message: string): void {
        this.#logs.push({ message });
        while (this.#logs.length > 20) {
            this.#logs.shift();
        }
        this.#updateLogs();
    }

    /**
     * 更新日志列表
     *
     * 将最新的日志内容依次设置给日志元素
     */
    #updateLogs(): void {
        for (let i = 0; i < 20; i++) {
            const elm = this.#elements[i]!;
            const index = this.#logs.length - 1 - i;
            if (index < 0) {
                elm.message = "";
                break;
            }
            const log = this.#logs[index]!;
            elm.message = log.message;
        }
    }

    /**
     * 清空日志
     */
    clear(): void {
        this.#logs = [];
        this.#updateLogs();
    }
}

define(LoggerElement);
